package cn.risebd.wechat.loader;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.google.common.base.Strings;

import cn.risebd.wechat.model.js.Ticket;
import cn.risebd.wechat.model.js.TicketType;

/**
 * @category 一个内存式Ticket加载器(生产环境不推荐使用)
 * @author 喝咖啡的蚂蚁
 * @copyright risebd.cn
 *
 */
public class DefaultTicketLoader implements TicketLoader {

	private final Map<TicketType, Ticket> tickets = new ConcurrentHashMap<>();

	@Override
	public String get(TicketType type) {
		Ticket t = tickets.get(type);
		return (t == null || Strings.isNullOrEmpty(t.getTicket()) || System.currentTimeMillis() > t.getExpireAt())
				? null : t.getTicket();
	}

	@Override
	public void refresh(Ticket ticket) {
		tickets.put(ticket.getType(), ticket);
	}
}
